﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using webapps.homefinance.Models;
using System.Data.Objects;

namespace webapps.homefinance.Controllers
{
    public class PlanningController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Save(Planning model)
        {
            HomeFinanceResponse response = new HomeFinanceResponse();

            try
            {
                if (model.dateBegin.HasValue)
                    model.dateEnd = model.dateBegin.Value.AddMonths(model.NuMeses - 1);

                using (Models.mainConnection conn = new mainConnection())
                {
                    conn.AddToPlannings(model);
                    conn.SaveChanges();
                }

                response.SetSuccess();
            }
            catch (Exception e)
            {
                response.SetException(e);
            }

            return Json(response);
        }

        public JsonResult GetList(int skip, int take)
        {
            HomeFinanceListResponse response = new HomeFinanceListResponse();

            try
            {
                using(Models.mainConnection conn = new mainConnection())
                {
                    var query = from r in conn.Plannings
                                select new { id = r.id, name = r.name, value = r.value, dateBegin = r.dateBegin.ToString(), dateEnd = r.dateEnd.ToString() }
                                ;

                    response.SetListData(query.OrderBy(r => r.name).Skip(skip).Take(take).ToArray());
                }

                response.SetSuccess();
            }
            catch (Exception e)
            {
                response.SetException(e);
            }

#if DEBUG
            return Json(response, JsonRequestBehavior.AllowGet);
#else
            return Json(response);
#endif
        }
    }
}
